# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JiangsuYangzhouPolicy(BaseTaxPolicySpider):
    name = 'jiangsu_yangzhou_qu_policy'

    province = '江苏省'
    city = '扬州市'
    # county = ''
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['扬州市广陵区人民政府', "广陵区", "https://www.yzglq.gov.cn/zfxxgk/fdzdgknr/qzfwj/index.html"],
            ['扬州市广陵区人民政府', "广陵区", "https://www.yzglq.gov.cn/zfxxgk/fdzdgknr/qzfbgswj/index.html"],
            ['扬州市邗江区人民政府', "邗江区", "https://www.hj.gov.cn/zfxxgk/fdzdgknr/zfwj/index.html"],
            ['扬州市江都区人民政府', "江都区", "http://www.jiangdu.gov.cn/zfxxgk/fdzdgknr/zfwj/index.html"],
            ['扬州市宝应县人民政府', "宝应县", "https://baoying.yangzhou.gov.cn/zfxxgk/fdzdgknr/zfwj/xzfwj/index.html"],
            ['扬州市宝应县人民政府', "宝应县", "https://baoying.yangzhou.gov.cn/zfxxgk/fdzdgknr/zfwj/xzfbwj/index.html"],
            ['扬州市仪征市人民政府', "仪征市", "https://www.yizheng.gov.cn/zfxxgk/fdzdgknr/zfwj/zffwj/index.html"],
            ['扬州市高邮市人民政府', "高邮市", "https://gaoyou.yangzhou.gov.cn/zwgk/fdzdgknr/zfwj/szfwj/index.html"],
            ['扬州市高邮市人民政府', "高邮市", "https://gaoyou.yangzhou.gov.cn/zwgk/fdzdgknr/zfwj/szfbwj/index.html"],
            ['扬州经济技术开发区', "扬州市经济开发区", "https://kfq.yangzhou.gov.cn/zfxxgk/fdzdgknr/bmwj/index.html"],

        ]:
            item = {'source': source, 'county': county}
            callback = self.parse_url
            yield scrapy.Request(url, callback=callback, meta={'item': item}, dont_filter=True)

    def parse_url(self, response, **kwargs):
        meta = response.meta
        # url = response.xpath("//a[text()='" + meta['path'] + "']/@href").get()
        if 'queryData=' in response.text:
            data = json.loads(response.xpath("//script[@id]/@querydata").get().replace("\'", '"'))
            url = response.xpath("//script[@id]/@url").get()
            pass
            data['paramJson'] = {'pageSize': 100, 'pageNo': 1}
            meta['params'] = data
            yield scrapy.Request(
                url=f"{response.urljoin(url)}?{urlencode(data)}",
                callback=self.parse_list,
                meta=meta,
            )
        else:
            print('not querydata')

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        # formdata = meta['formdata']
        res = scrapy.Selector(text=response.json()['data']['html'])
        elem_list = res.xpath('//li')
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['title'] = elem.xpath(""".//a[@title]/@title""").get() or elem.xpath(""".//a/text()""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("./span/text()").get()
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if (self.get_next or self.get_next == '0') and meta.get('is_next') is not False:
            total_count = int(res.xpath("//div/@count").get() or 0)
            total_page = math.ceil(total_count / 100)
            print('total', total_page, )
            data = meta['params']
            for page_num in range(2, total_page + 1):
                data['paramJson']['pageNo'] = str(page_num)
                meta.update({'item': prev_item, 'is_next': False})
                # print(params)
                yield scrapy.Request(url=f"{response.url.split('?')[0]}?{urlencode(data)}", callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = item['title'] if item['title'] else response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath(
        #     """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
        #     "//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangsu_yangzhou_qu_policy -a get_next=0".split())
